//
//  SunSystemViewController.swift
//  FlutterTest
//
//  Created by 张鑫 on 2020/8/25.
//  Copyright © 2020 www.lionaitech.com. All rights reserved.
//

import UIKit
import SceneKit

class SunSystemViewController: UIViewController {
    
    var sunNode: SCNNode?
    var earthNode: SCNNode?
    var moonNode: SCNNode?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "太阳系"
        
        createScene()
        createSun()
        createEarth()
        createMoon()
        
        let link = CADisplayLink(target: self, selector: #selector(displayLink))
        link.add(to: RunLoop.main, forMode: .default)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    var scene: SCNScene?
    func createScene() {
        //设置摄像机架设点
        let cameraNode = SCNNode()
        cameraNode.position = SCNVector3(0, 25, 100)
        cameraNode.camera = SCNCamera()
        cameraNode.camera?.zFar = 200
        cameraNode.camera?.automaticallyAdjustsZRange = true
        cameraNode.rotation = SCNVector4(1, 0, 0, -Double.pi/16)
        
        
        //设置光源点
        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light?.type = .omni
        lightNode.position = SCNVector3(0, 10, 10)
        
        //设置周围环境
        let ambientLightNode = SCNNode()
        ambientLightNode.light = SCNLight()
        ambientLightNode.light?.type = .ambient
        ambientLightNode.light?.color = UIColor.lightGray
        
        // 创建场景，添加各个元素
        //        scene = SCNScene(named: "art.scnassets/ship.scn")
        scene = SCNScene()
        
        scene?.rootNode.addChildNode(cameraNode)
        //        scene?.rootNode.addChildNode(lightNode)
        //        scene?.rootNode.addChildNode(ambientLightNode)
//        scene?.background.contents = "art.scnassets/SunSysSource/earth-diffuse.jpg"
//        scene?.background.intensity = 0.1
//        scene?.background.wrapT = .repeat
//        scene?.background.wrapS = .repeat
        scene?.lightingEnvironment.contents = "art.scnassets/SunSysSource/earth-diffuse.jpg"
        
        let threeDView = SCNView(frame: CGRect.zero)
        threeDView.translatesAutoresizingMaskIntoConstraints = false
        threeDView.scene = scene
        threeDView.allowsCameraControl = true
        threeDView.showsStatistics = true
        threeDView.backgroundColor = UIColor.black
        threeDView.preferredFramesPerSecond = 30
        view.addSubview(threeDView)
        
        
        threeDView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        threeDView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        threeDView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        threeDView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
    
    func createSun() {
        
        let deffuseAni = CABasicAnimation(keyPath: "contentsTransform")
        deffuseAni.duration = 10.0
        deffuseAni.fromValue = CATransform3DConcat(CATransform3DMakeTranslation(0, 0, 0), CATransform3DMakeScale(3, 3, 3))
        deffuseAni.toValue = CATransform3DConcat(CATransform3DMakeTranslation(1, 0, 0), CATransform3DMakeScale(3, 3, 3))
        deffuseAni.repeatCount = .greatestFiniteMagnitude
        
        
        let multiplyAni = CABasicAnimation(keyPath: "contentsTransform")
        multiplyAni.duration = 30.0
        multiplyAni.fromValue = CATransform3DConcat(CATransform3DMakeTranslation(0, 0, 0), CATransform3DMakeScale(5, 5, 5))
        multiplyAni.toValue = CATransform3DConcat(CATransform3DMakeTranslation(1, 0, 0), CATransform3DMakeScale(5, 5, 5))
        multiplyAni.repeatCount = .greatestFiniteMagnitude
        
        
        sunNode = SCNNode()
        sunNode?.position = SCNVector3(0, 0, 0)
        sunNode?.geometry = SCNSphere(radius: 15)
        sunNode?.geometry?.firstMaterial?.diffuse.contents = "art.scnassets/SunSysSource/sun.jpg"
        sunNode?.geometry?.firstMaterial?.diffuse.wrapS = .repeat
        sunNode?.geometry?.firstMaterial?.diffuse.wrapT = .repeat
        sunNode?.geometry?.firstMaterial?.diffuse.addAnimation(deffuseAni, forKey: "sun-texture")
        
        sunNode?.geometry?.firstMaterial?.multiply.contents = "art.scnassets/SunSysSource/sun.jpg"
        sunNode?.geometry?.firstMaterial?.multiply.wrapS = .repeat
        sunNode?.geometry?.firstMaterial?.multiply.wrapT = .repeat
        sunNode?.geometry?.firstMaterial?.multiply.addAnimation(multiplyAni, forKey: "sun-texture2")

        sunNode?.geometry?.firstMaterial?.multiply.intensity = 0.5
        sunNode?.geometry?.firstMaterial?.lightingModel = .constant
//        sunNode?.geometry?.firstMaterial?.locksAmbientWithDiffuse = true
        
        scene?.rootNode.addChildNode(sunNode!)
    }
    
    func createEarth() {
        
        earthNode = SCNNode()
        earthNode?.position = SCNVector3(55, 0, 0)
        earthNode?.geometry = SCNSphere(radius: 5)
        earthNode?.geometry?.firstMaterial?.diffuse.contents = "art.scnassets/SunSysSource/earth-diffuse-mini.jpg"
        earthNode?.geometry?.firstMaterial?.emission.contents = "art.scnassets/SunSysSource/earth-emissive-mini.jpg"
        earthNode?.geometry?.firstMaterial?.specular.contents = "art.scnassets/SunSysSource/earth-specular-mini.jpg"

        earthNode?.geometry?.firstMaterial?.locksAmbientWithDiffuse = true

        earthNode?.geometry?.firstMaterial?.shininess = 0.1;
        earthNode?.geometry?.firstMaterial?.specular.intensity = 0.5
        scene?.rootNode.addChildNode(earthNode!)
        
        let cloudNode = SCNNode()
        cloudNode.geometry = SCNSphere(radius: 5.5)
        cloudNode.geometry?.firstMaterial?.transparent.contents = "art.scnassets/SunSysSource/cloudsTransparency.png"
        cloudNode.geometry?.firstMaterial?.transparencyMode = .rgbZero
        cloudNode.opacity = 0.5
        earthNode?.addChildNode(cloudNode)
        
        earthNode?.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 0.5)))
        
        let duration = 10.0 / 360.0
        
        let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) in
            guard elapsedTime >= CGFloat(duration) else {
                return
            }
            let pos = node.position
            let angle = -Double.pi / 180
            
            let x = Double(pos.x - 0) * cos(angle) - Double(pos.z - 0) * sin(angle) + 0
            let z = Double(pos.x - 0) * sin(angle) + Double(pos.z - 0) * cos(angle) + 0
            
            node.position = SCNVector3(x, Double(pos.y), z)
            
        }
        
        earthNode?.runAction(SCNAction.repeatForever(action))
        
    }
    
    func createMoon() {
        moonNode = SCNNode()
        moonNode?.position = SCNVector3(15, 0, 0)
        moonNode?.geometry = SCNSphere(radius: 3)
        moonNode?.geometry?.firstMaterial?.diffuse.contents = "art.scnassets/SunSysSource/moon.jpg"
        earthNode?.addChildNode(moonNode!)
        
        moonNode?.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 0.5)))
        
        let duration = 1.0/360
        
        let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) in
            guard elapsedTime >= CGFloat(duration) else {
                return
            }
            let pos = node.position
            let angle = Double.pi / 180
            
            let x = Double(pos.x) * cos(angle) - Double(pos.z) * sin(angle)
            let z = Double(pos.x) * sin(angle) + Double(pos.z) * cos(angle)
            
            node.position = SCNVector3(x, Double(pos.y), z)
            
        }
        moonNode?.runAction(SCNAction.repeatForever(action))
        
    }
    
    @objc func displayLink() {
//        print("\(Date())")
    }
    
    
    /**
     太阳半径 695500
     地球半径 6371
     月球半径 1738
     
     
     日地距离 149597870
     地月距离 384000
     */
    
    
}
